<!-- eslint-disable vue/no-use-v-if-with-v-for -->
<!-- eslint-disable vue/valid-v-slot -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachFormRef" :model="seachForm">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="id" hide-label>
                    <a-input-group style="width: 100%">
                      <a-select
                        style="width: 50%"
                        @change="typeFn"
                        v-model="type"
                        placeholder="first"
                      >
                        <a-option v-for="item in typeLists" :key="item.name" :value="item.value">{{
                          item.name
                        }}</a-option>
                      </a-select>
                      <Inputs :cards="typeText" @update="cardFn" />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="userId" hide-label>
                    <a-select
                      v-model="seachForm.userId"
                      allow-clear
                      allow-search
                      placeholder="请选择客户"
                      :options="userList"
                      :virtual-list-props="{ height: 200 }"
                  /></a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="rebateState" hide-label>
                    <a-select
                      v-model="seachForm.rebateState"
                      placeholder="请选择返佣状态"
                      allow-clear
                    >
                      <a-option :value="0">等待返佣</a-option>
                      <a-option :value="1">返佣成功</a-option>
                      <a-option :value="2">返佣失败</a-option>
                      <a-option :value="3">返佣收回</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="commissionState" hide-label>
                    <a-select
                      v-model="seachForm.commissionState"
                      placeholder="请选择佣金状态"
                      allow-clear
                    >
                      <a-option :value="0">已冻结</a-option>
                      <a-option :value="1">已成功</a-option>
                      <a-option :value="2">已失败</a-option>
                      <a-option :value="3">已收回</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="commissionRule" hide-label>
                    <a-select
                      v-model="seachForm.commissionRule"
                      placeholder="请选择佣金规则"
                      allow-clear
                    >
                      <a-option :value="0">秒返</a-option>
                      <a-option :value="1">次月底返</a-option>
                      <a-option :value="2">月月返</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      v-model="seachForm.addTime"
                      style="width: 100%"
                      show-time
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      placeholder="请选择开始时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      v-model="seachForm.endTime"
                      style="width: 100%"
                      show-time
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      placeholder="请选择结束时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addRebateAmount" hide-label>
                    <a-input-group style="width: 100%">
                      <a-input
                        hide-button
                        v-model="seachForm.addRebateAmount"
                        placeholder="开始订单返佣"
                      />
                      <a-input
                        hide-button
                        v-model="seachForm.endRebateAmount"
                        placeholder="结束订单返佣"
                      />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addCommission" hide-label>
                    <a-input-group style="width: 100%">
                      <a-input
                        hide-button
                        v-model="seachForm.addCommission"
                        placeholder="开始商品佣金"
                      />
                      <a-input
                        hide-button
                        v-model="seachForm.endCommission"
                        placeholder="结束商品佣金"
                      />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="'/app/mall/order/commission/list'"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button v-permission="rebateList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button
            type="outline"
            v-permission="rebateListexport"
            :loading="loading"
            @click="exportList"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          :scrollbar="true"
          :scroll="{ x: 1200 }"
          table-layout-fixed
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :width="item.width"
              :ellipsis="true"
              :tooltip="true"
              :title="(item.title as string)"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
            >
              <template v-if="item.key === 'rebateState'" #cell="{ record }">
                <a-tag v-if="record.rebateState === 0">等待返佣</a-tag>
                <a-tag color="blue" v-else-if="record.rebateState === 1">返佣成功</a-tag>
                <a-tag color="red" v-else-if="record.rebateState === 2">返佣失败</a-tag>
                <a-tag color="red" v-else-if="record.rebateState === 3">收回返佣</a-tag>
              </template>
              <template v-if="item.key === 'state'" #cell="{ record }">
                <a-tag v-if="record.commissionState === 0">已冻结</a-tag>
                <a-tag color="blue" v-else-if="record.commissionState === 1">已成功</a-tag>
                <a-tag color="red" v-else-if="record.commissionState === 2">已失败</a-tag>
                <a-tag color="red" v-else-if="record.commissionState === 3">已收回</a-tag>
              </template>
              <template v-if="item.key === 'commission'" #cell="{ record }">
                <span @click="detailFn(record)"> {{ record.commission }}</span>
              </template>
              <template v-else-if="item.key === 'action'" #cell="{ record }">
                <a-button
                  v-permission="'/app/mall/order/commission/recycling'"
                  type="text"
                  @click="openHui(record)"
                  >收回</a-button
                >
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <!-- 详情 -->
    <a-modal
      title-align="start"
      v-model:visible="visible"
      :mask-closable="false"
      width="800px"
      title="月月返详情"
    >
      <a-table
        :bordered="{ wrapper: tables.bordered, cell: tables.bordered }"
        :stripe="(tables.striped as boolean)"
        :data="tableData2"
        :pagination="false"
        :column-resizable="true"
        :rowKey="rowKey"
        table-layout-fixed
      >
        <template #columns>
          <a-table-column
            v-for="item of commissitionCoumn"
            :key="item.key"
            :title="(item.title as string)"
            :data-index="(item.key as string)"
            :width="item.width"
            :ellipsis="true"
            :tooltip="true"
          >
            <template v-if="item.key === 'rebateTime'" #cell="{ record }">
              <span>
                {{ record.rebateTime ? record.rebateTime : '- - -' }}
              </span>
            </template>
            <template v-if="item.key === 'state'" #cell="{ record }">
              <span>
                {{
                  record.state == 1
                    ? '已结算'
                    : record.state == 0
                    ? '冻结中'
                    : record.state == 2
                    ? '已失败'
                    : '已回收'
                }}
              </span>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
    <!-- 详情 -->
    <a-modal
      title-align="start"
      v-model:visible="infoDetailVisible"
      :mask-closable="false"
      width="600px"
      title="回收返佣"
    >
      <a-form ref="flowRef" :auto-label-width="true" :model="infoDetail">
        <a-form-item field="type" label="操作类型">
          <a-radio-group v-model="infoDetail.type" class="radio-bcg">
            <a-radio :value="0">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div>
                  </div>
                  <div className="custom-radio-card-title">全部</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="1">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div>
                  </div>
                  <div className="custom-radio-card-title">订单返佣</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="2">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div>
                  </div>
                  <div className="custom-radio-card-title">商品佣金</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="infoDetail.type == 2 && everyList.length > 0"
          field="month"
          label="月月返"
          :rules="[{ required: true, message: '月月返不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-select
            v-model="infoDetail.month"
            style="width: 100%"
            multiple
            placeholder="请选择回收期数"
            allow-clear
            allow-search
          >
            <a-option v-for="item in everyList" :key="item.month" :value="item.month">{{
              item.monthName
            }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="monthCFn">取消</a-button>
          <a-button type="primary" :loading="loadings" @click="monthSub">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import Inputs from '@/views/finance/components/input.vue'
  import { onMounted, reactive, ref } from 'vue'
  import useCommonStore from '@/store/modules/common'
  import { usePagination, useRowKey, useTable, useTableHeight } from '@/hooks/table'
  import { formpost, get } from '@/api/http'
  import { rebateList, rebateListexport, rebaterecovery } from '@/api/url'
  import { Modal, Message } from '@arco-design/web-vue'
  import { mount } from 'sortablejs'
  const infoDetail: any = ref({
    type: 0,
    month: [],
  })
  const infoDetailVisible = ref(false)
  const everyList: any = ref([])
  function openHui(val: any) {
    infoDetail.value.id = val.id
    if (val.everyMonthCommission) {
      everyList.value = []
      val.everyMonthCommission.forEach((item: any) => {
        item.monthName = '第' + item.month + '月'
        everyList.value.push(item)
      })
    }
    infoDetailVisible.value = true
  }
  const flowRef = ref()
  function monthCFn() {
    infoDetail.value = {
      type: 0,
      month: [],
    }
    infoDetailVisible.value = false
  }
  const loadings = ref(false)
  function monthSub() {
    flowRef.value?.validate().then((error: any) => {
      if (!error) {
        loadings.value = true
        get({
          url: '/app/mall/order/commission/recycling',
          data: () => {
            return {
              ...infoDetail.value,
              month: infoDetail.value.month.toString(),
            }
          },
        })
          .then((res: any) => {
            if (res.code == 0) {
              Message.success(res.msg)
              loadings.value = false
              monthCFn()
              doRefresh()
            }
          })
          .catch(() => {
            loadings.value = false
          })
      }
    })
  }
  const commissitionCoumn = [
    {
      title: '月份',
      key: 'month',
      dataIndex: 'month',
      align: 'center',
      checked: true,
      width: 100,
    },
    {
      title: '返佣金额',
      key: 'commission',
      dataIndex: 'commission',
      align: 'center',
      checked: true,
      width: 100,
    },
    {
      title: '返佣状态',
      key: 'state',
      dataIndex: 'state',
      align: 'center',
      checked: true,
      width: 120,
    },
    {
      title: '返佣时间',
      key: 'rebateTime',
      dataIndex: 'rebateTime',
      align: 'center',
      checked: true,
      width: 180,
    },
  ]
  const typeText = ref('')
  const type = ref('systemTradeNos')
  const typeLists = ref([
    {
      name: '订单号',
      value: 'systemTradeNos',
    },
    {
      name: '订单ID',
      value: 'orderIds',
    },
    {
      name: '佣金ID',
      value: 'ids',
    },
  ])
  function typeFn() {
    typeText.value = ''
    for (var key in seachForm.value) {
      if (key !== type.value) {
        seachForm.value[key] = ''
      }
    }
  }
  const tableData2: any = ref([])
  //获取详情
  function detailFn(val: any) {
    if (val.everyMonthCommission) {
      tableData2.value = val.everyMonthCommission
      visible.value = true
    }
  }

  const seachForm = ref({
    ids: '', //             佣金ID
    orderIds: '', //         订单ID
    systemTradeNos: '', //   系统订单号
    userId: '', //           用户ID
    commissionRule: '', //   佣金类型
    rebateState: '', //      返佣状态
    commissionState: '', //  佣金状态
    addTime: '', //          开始时间
    endTime: '', //          结束时间
    addRebateAmount: '', //  开始订单返佣
    endRebateAmount: '', //  结束订单返佣
    addCommission: '', //    开始商品佣金
    endCommission: '', //    结束商品佣金
  })
  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })
  const seachFormRef = ref()
  const common = useCommonStore()
  const userList: any = ref([])
  const channelList: any = ref([])
  const serieList: any = ref([])
  const mealList: any = ref([])
  const tableLoading = ref(false)
  const pagination = usePagination(doRefresh)
  const table = useTable()
  const loading = ref(false)
  const tableFooterRef = ref()
  const rowKey = useRowKey('id')
  const detail: any = ref({
    card: {},
    order: {},
    user: {},
  })
  const visible = ref(false)
  const tableColumns: any = reactive({
    list: [
      {
        title: '佣金ID',
        key: 'id',
        dataIndex: 'id',
        checked: true,
        width: 120,
      },
      {
        title: '客户账号',
        key: 'userName',
        dataIndex: 'userName',
        ellipsis: true,
        tooltip: true,
        checked: true,
        width: 130,
      },
      {
        title: '订单号',
        key: 'systemTradeNo',
        dataIndex: 'systemTradeNo',
        checked: true,
        width: 200,
      },
      {
        title: '商品佣金',
        key: 'commission',
        dataIndex: 'commission',
        checked: true,
        width: 120,
      },
      {
        title: '佣金状态',
        key: 'state',
        dataIndex: 'state',
        checked: true,
        width: 120,
      },
      {
        title: '订单返佣',
        key: 'rebateAmount',
        dataIndex: 'rebateAmount',
        checked: true,
        width: 120,
      },
      {
        title: '返佣状态',
        key: 'rebateState',
        dataIndex: 'rebateState',
        checked: true,
        width: 120,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'action',
        dataIndex: 'action',
        checked: true,
        width: 70,
        fixed: 'right',
      },
    ],
  })
  //获取多卡
  function cardFn(value: any) {
    console.log(value)
    for (var key in seachForm.value) {
      if (key == type.value) {
        seachForm.value[key] = value
      }
    }
    typeText.value = value
  }

  //导出
  function exportList() {
    loading.value = true
    common.downLoadPosts(rebateListexport, seachForm.value, '返佣列表').then(() => {
      loading.value = false
    })
  }
  //重置
  function resetSeach() {
    seachFormRef.value?.resetFields()
    // seachForm.value.addAmount = ''
    // seachForm.value.endAmount = ''
    // seachForm.value.cards = ''
    seachForm.value.addRebateAmount = '' //  开始订单返佣
    seachForm.value.endRebateAmount = '' //  结束订单返佣
    seachForm.value.addCommission = '' //    开始商品佣金
    seachForm.value.endCommission = '' //    结束商品佣金
    seachForm.value.systemTradeNos = ''
    seachForm.value.ids = ''
    seachForm.value.orderIds = ''
    typeText.value = ''
    doRefresh(1)
  }
  //搜索
  function doRefresh(value?: number) {
    // eslint-disable-next-line prettier/prettier
    tableLoading.value = true
    if (value) {
      pagination.page = value
    }
    get({
      url: '/app/mall/order/commission/list',
      data: () => {
        return {
          page: pagination.page,
          size: pagination.pageSize,
          ...seachForm.value,
        }
      },
    })
      .then((res) => {
        tableLoading.value = false
        table.handleSuccess(res.data.list)
        pagination.setTotalSize((res.data as any).totalSize)
      })
      .catch(console.log)
  }
  //全部客户
  function getUser() {
    common.userLists().then((res: any) => {
      userList.value = res.data
    })
  }
  //全部渠道
  function getChannel() {
    common.channels().then((res: any) => {
      channelList.value = res.data
    })
  }
  //全部系列
  function getSeries() {
    common.seriess().then((res: any) => {
      serieList.value = res.data
    })
  }
  //全部套餐
  function getMeal() {
    common.mealListFn().then((res: any) => {
      mealList.value = res.data
    })
  }
  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }
  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }
  onMounted(async () => {
    await getUser()
    await getChannel()
    await getSeries()
    await getMeal()
    await doRefresh()
  })
</script>
<style lang="less" scoped>
  :deep(.arco-modal) {
    .arco-modal-footer {
      text-align: right !important;
    }
  }
  :deep(.arco-modal-header .arco-modal-title) {
    display: flex;
    justify-content: flex-start !important;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
</style>
